import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const request = axios.create({
    baseURL: 'http://localhost:5000/api',
    timeout: 60000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        console.log('Current token:', token) // 调试日志

        if (!token) {
            console.warn('No token found in localStorage')
            router.push('/login')
            return Promise.reject('No token found')
        }

        // 确保 headers 对象存在
        config.headers = config.headers || {}
        
        // 设置 Authorization 头
        config.headers['Authorization'] = `Bearer ${token}`
        
        // 调试日志
        console.log('Request headers:', config.headers)
        console.log('Full config:', {
            url: config.url,
            method: config.method,
            baseURL: config.baseURL,
            headers: config.headers,
            data: config.data
        })

        return config
    },
    error => {
        console.error('Request error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        console.error('Response error:', error)
        if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
            // 处理超时错误
            ElMessage.error('请求超时，请重试')
        } else {
            const message = error.response?.data?.message || '请求失败'
            ElMessage.error(message)
        }
        return Promise.reject(error)
    }
)

export default request 